package com.zzyl.framework.interceptor;

import com.zzyl.common.core.domain.model.LoginUser;
import com.zzyl.framework.web.service.TokenService;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@Slf4j
public class MemberInterceptor implements HandlerInterceptor {
    @Autowired
    private TokenService tokenService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取token，并解析
        log.info("拦截器");
        String token = request.getHeader("Authorization");
        if (token == null) {
            return true;
        }
        Claims claims = tokenService.parseToken(token);
        Object userId = claims.get("id");
        System.out.println("setUser thread: " + Thread.currentThread().getId());
        ThreadLocalUser.setUser(Long.parseLong(userId.toString()));
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 请求处理完成后清理 ThreadLocalUser
        ThreadLocalUser.remove();
    }
}
